<?php

namespace app\admin\controller;

use app\admin\model\AdminAdmin;
use app\admin\model\AdminAdminLog;
use app\admin\model\AdminRole;
use Exception;
use Respect\Validation\Exceptions\ValidationException;
use Respect\Validation\Validator as v;
use support\Request;
use support\Response;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;

class Admin_admin extends Base
{
    /**
     * 管理员
     * @param  Request  $request
     * @return string|Response
     */
    public function index(Request $request)
    {
        if ($request->isAjax()) {
            //按用户名
            if ($search = $request->get('username')) {
                $this->where[] = ['username', 'like', "%".$search."%"];
            }
            $list = $this->model->order('id', 'desc')->where('id', '>',
                '1')->withoutField('password,rand_key,delete_time')->where($this->where)->paginate([
                'list_rows' => $request->input('limit'), 'page' => $request->input('page'),
            ]);
            $data = [
                'msg'   => '',
                'data'  => $list->items(),
                'code'  => 0,
                'count' => $list->total(),
                'limit' => $request->get('limit'),
            ];
            return json($data);
        }
        return view('adminadmin/index');
    }

    /**
     * 添加
     * @param  Request  $request
     * @return
     */
    public function add(Request $request)
    {
        if ($request->isAjax()) {
            $data = $request->post();
            //验证
            try {
                $data = v::input($request->post(), [
                    'username' => v::alnum()->length(1, 64)->setName('用户名'),
                    'password' => v::length(5, 64)->setName('密码'),
                    'nickname' => v::length(1, 64)->setName('昵称'),
                ]);
                if ($this->model->where(['username' => $request->post('username')])->find()) {
                    throw new Exception('用户名已存在');
                }
            } catch (ValidationException $e) {
                return json(['code' => 201, 'msg' => '添加失败', 'data' => $e->getMessage()]);
            }
            try {
                $password = set_password($data['password']);
                $this->model->create(array_merge($data, [
                    'password' => $password,
                ]));
            } catch (Exception $e) {
                return json(['code' => 201, 'msg' => '添加失败', 'data' => $e->getMessage()]);
            }
            return json(['code' => 200, 'msg' => '添加成功']);
        }
        return view('adminadmin/add');
    }

    /**
     * 编辑
     * @param  Request  $request
     * @return string|Response
     * @throws Exception
     */
    public function edit(Request $request)
    {
        $id = $request->input('id');
        $model = $this->model->find($id);
        if ($request->isAjax()) {
            $data = $request->post();
            $data['id'] = $model['id'];
            //验证
            try {
                $data = v::input($request->post(), [
                    'username' => v::alnum()->length(1, 64)->setName('用户名'),
                    'nickname' => v::length(1, 64)->setName('昵称'),
                ]);
                if ($this->model->where(['username' => $request->post('username')])->find()) {
                    throw new Exception('用户名已存在');
                }
            } catch (ValidationException $e) {
                return json(['code' => 201, 'msg' => '添加失败', 'data' => $e->getMessage()]);
            }

            //是否需要修改密码
            if (!empty($data['password'])) {
                $model->password = set_password($data['password']);
                $model->token = null;
            }
            $model->username = $data['username'];
            $model->nickname = $data['nickname'];
            try {
                $model->save();
            } catch (Exception $e) {
                return json(['code' => 201, 'msg' => '更新失败', 'data' => $e->getMessage()]);
            }
            return json(['code' => 200, 'msg' => '更新成功']);
        }
        return view('adminadmin/edit', [
            'model' => $model,
        ]);
    }

    /**
     * 禁用，启用
     * @param  Request  $request
     */
    public function status(Request $request)
    {
        $id = $request->input('id');
        $model = $this->model->find($id);
        if ($model->isEmpty()) {
            return json(['code' => 201, 'msg' => '数据不存在']);
        }
        try {
            $model->save([
                'status' => $request->post('status'),
                'token'  => null,
            ]);
        } catch (Exception $e) {
            return json(['code' => 201, 'msg' => '更新失败', 'data' => $e->getMessage()]);
        }
        return json(['code' => 200, 'msg' => '更新成功']);
    }

    /**
     * 删除
     * @param  Request  $request
     * @return Response
     */
    public function del(Request $request)
    {
        return json(['code' => 201, 'msg' => '演示禁止删除']);
        $id = $request->input('id');
        $model = $this->model->find($id);
        if ($model->isEmpty()) {
            return json(['code' => 201, 'msg' => '数据不存在']);
        }
        try {
            $model->delete();
            Db::table('admin_admin_role')->where('admin_id', $id)->delete();
        } catch (Exception $e) {
            return json(['code' => 201, 'msg' => '删除失败', 'data' => $e->getMessage()]);
        }
        return json(['code' => 200, 'msg' => '删除成功']);
    }

    /**
     * 选中删除
     * @param  Request  $request
     */
    public function del_all(Request $request)
    {
        return json(['code' => 201, 'msg' => '演示禁止删除']);
        $ids = $request->post('ids');
        if (!is_array($ids)) {
            return json(['code' => 201, 'msg' => '参数错误']);
        }
        try {
            $this->model->destroy($ids);
            Db::table('admin_admin_role')->whereIn('admin_id', $ids)->delete();
        } catch (Exception $e) {
            return json(['code' => 201, 'msg' => '删除失败', 'data' => $e->getMessage()]);
        }
        return json(['code' => 200, 'msg' => '删除成功']);
    }

    /**
     * 用户分配角色
     * @param  Request  $request
     * @return
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function role(Request $request)
    {
        $id = $request->input('id');
        $admin = $this->model->with('roles')->where('id', $id)->find();
        $roles = AdminRole::select();
        foreach ($roles as $k => $role) {
            if (isset($admin->roles) && !$admin->roles->isEmpty()) {
                foreach ($admin->roles as $v) {
                    if ($role['id'] == $v['id']) {
                        $roles[$k]['own'] = true;
                    }
                }
            }
        }
        if ($request->isAjax()) {
            $postRoles = $request->post('roles') ?? '';
            if (!$postRoles) {
                return json(['code' => 201, 'msg' => '至少选择一项']);
            }
            Db::startTrans();
            try {
                //清除原先的角色
                Db::name('admin_admin_role')->where('admin_id', $id)->delete();
                //添加新的角色
                foreach ($postRoles as $v) {
                    Db::name('admin_admin_role')->insert([
                        'admin_id' => $admin['id'],
                        'role_id'  => $v,
                    ]);
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                return json(['code' => 201, 'msg' => '更新失败', 'data' => $e->getMessage()]);
            }
            return json(['code' => 200, 'msg' => '更新成功']);
        }
        return view('adminadmin/role', [
            'admin' => $admin,
            'roles' => $roles,
        ]);
    }

    /**
     * 回收站
     */
    public function recycle(Request $request)
    {
        if ($request->isAjax()) {
            if ($request->Method() == 'POST') {
                $ids = $request->input('ids');
                if (!is_array($ids)) {
                    return ['msg' => '参数错误', 'code' => '201'];
                }
                try {
                    if ($request->input('type') == '1') {
                        $data = $this->model->onlyTrashed()->whereIn('id', $ids)->select();
                        foreach ($data as $k) {
                            $k->restore();
                        }
                    } else {
                        $this->model->destroy($ids, true);
                    }
                } catch (Exception $e) {
                    return json(['code' => 201, 'msg' => '删除失败', 'data' => $e->getMessage()]);
                }
                return json(['code' => 200, 'msg' => '删除成功']);
            }
            //按用户名
            if ($search = $request->input('username')) {
                $this->where[] = ['username', 'like', "%".$search."%"];
            }
            $list = $this->model->onlyTrashed()->order('id',
                'desc')->withoutField('password,delete_time')->where($this->where)->paginate([
                'list_rows' => $request->input('limit'), 'page' => $request->input('page'),
            ]);
            $data = [
                'msg'   => '',
                'data'  => $list->items(),
                'code'  => 0,
                'count' => $list->total(),
                'limit' => $request->get('limit'),
            ];
            return json($data);
        }
        return view('adminadmin/recycle');
    }

    public function log(Request $request)
    {
        if ($request->isAjax()) {
            if ($search = $request->get('uid')) {
                $this->where[] = ['uid', '=', $search];
            }
            $list = (new AdminAdminLog)->with('log')->order('id',
                'desc')->where($this->where)->paginate([
                'list_rows' => $request->input('limit'), 'page' => $request->input('page'),
            ]);
            $data = [
                'msg'   => '',
                'data'  => $list->items(),
                'code'  => 0,
                'count' => $list->total(),
                'limit' => $request->get('limit'),
            ];
            return json($data);
        }
        return view('adminadmin/log');
    }

    /**
     * 清空日志
     */
    public function del_log()
    {
        return json(['code' => 201, 'msg' => '演示禁止删除']);
        Db::table('admin_admin_log')->delete(true);
        return json(['code' => 200, 'msg' => '删除成功']);
    }

    protected function initialize()
    {
        $this->model = new AdminAdmin;
    }

}
